<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar title="搜索结果" left-arrow @click-left="$router.go(-1)" fixed />
    </div>

    <!-- 文章等待加载中 -->
    <van-loading v-if="searchList.length === 0" size="24px" color="#007bff">文章加载中...</van-loading>

    <van-list v-else v-model="loading" :finished="finished" :immediate-check="false" finished-text="没有更多了"
              @load="onLoad">
      <ArticleItem v-for="item in searchList" :key="item.art_id" :artObj="item" :iconShow="false"
                   @click.native="itemClickFn(item.art_id)">
      </ArticleItem>
    </van-list>
  </div>
</template>

<script>
import { searchResultAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  name: 'SearchResult',
  data() {
    return {
      loading: false, // 上拉加载是否正在进行
      finished: false, // 上拉加载是否正在完成
      page: 1, // 搜索结果页数
      searchList: [] // 搜索结果列表
    }
  },
  created() {
    this.asearchResultFn(this.page)
  },
  methods: {
    // 获取搜索结果
    async asearchResultFn(page) {
      const { data: res } = await searchResultAPI({
        page,
        q: this.$route.params.kw
      })
      this.searchList = [...this.searchList, ...res.data.results]
      this.loading = false
      if (res.data.results.length === 0) {
        this.finished = true
      }
    },
    // 上拉加载更多
    onLoad() {
      this.asearchResultFn(++this.page)
    },
    // 点击跳转到文章详细页面
    itemClickFn(artId) {
      this.$router.push({
        path: `/articleDetail?art_id=${artId}`
      })
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
.van-loading {
  text-align: center;
}
</style>
